package com.uetoken.cn.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.ips.wcpaysdk.IpsPayUtil;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.uetoken.cn.R;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.bean.BlockchainPursesBean;
import com.uetoken.cn.bean.ConfigBean;
import com.uetoken.cn.bean.PurseListBean;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;
import com.uetoken.cn.utils.AppUtils;
import com.uetoken.cn.utils.BlockchainUtils;
import com.uetoken.cn.utils.ClipboardHelper;
import com.uetoken.cn.utils.GlideApp;
import com.uetoken.cn.utils.Save2DecimalUtils;
import com.uetoken.cn.utils.ZXingUtils;
import com.uetoken.cn.view.popwindow.CurrencySelectPopWindow;
import com.umeng.commonsdk.debug.E;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.qrcode.zxing.ZXingView;
import okhttp3.Call;

import static com.uetoken.cn.common.Constant.EOS_PURSE;

public class ChargeMoneyActivity extends BaseActivity implements WebResponse, CurrencySelectPopWindow.OnPurseListener {

    @BindView(R.id.topbar)
    QMUITopBar mTopbar;
    @BindView(R.id.childPurseIv)
    ImageView childPurseIv;
    @BindView(R.id.goinLayout)
    RelativeLayout goinLayout;
    @BindView(R.id.childPurseNameTv)
    TextView childPurseNameTv;
    @BindView(R.id.childPurseBalanceTv)
    TextView childPurseBalanceTv;
    @BindView(R.id.chargeMoneyAddressTv)
    TextView chargeMoneyAddressTv;
    @BindView(R.id.chargeMoneyQRIv)
    ImageView chargeMoneyQRIv;
    @BindView(R.id.saveQRBtn)
    Button saveQRBtn;
    @BindView(R.id.addressMoneyTv)
    TextView addressMoneyTv;
    @BindView(R.id.copyAddressBtn)
    Button copyAddressBtn;
    @BindView(R.id.explainIv)
    ImageView explainIv;
    @BindView(R.id.explainTv)
    TextView explainTv;
    @BindView(R.id.explainLayout)
    RelativeLayout explainLayout;
    @BindView(R.id.memoTv)
    TextView memoTv;
    @BindView(R.id.copyMemoBtn)
    Button copyMemoBtn;


    /**
     * 获取钱包获取钱包地址网络请求码
     */
    private static final int NETWORK_REQUEST_PURSE_ADDRESS = 10;
    /**
     * 钱包转账网络请求码
     */
    private static final int NETWORK_REQUEST_SUB_PURSES = 11;
    /**
     * 获取区块链钱包网络请求码
     * Blockchain
     */
    private static final int REQUEST_NETWORK_BLOCKCHAIN_PURSE_LIST = 12;
    /**
     * 用户ID
     */
    private String nodeid;
    /**
     * 钱包序号
     */
    private String mId;
    /**
     * 子钱包id
     */
    private String purseId;
    /**
     * 子钱包名字
     */
    private String purseName = "";
    /**
     * 子钱包余额
     */
    private String balance = "";
    /**
     * 钱包类型
     */
    private String purseconfigid = "";
    private String purseaddress = "";
    private String purseunitname = "";
    private String minnumber = "0";
    private String depositTip = "";
    private int selPosition;
    private Bitmap bitmap;
    private String memoaddress = "";
    private String eosdeposittip;//充币eos--提示说明
    private int pursetype;//钱包类型

    private List<BlockchainPursesBean.DataBean> pursesList;
    private CurrencySelectPopWindow mCurrencySelectPopWindow;
    private PurseListBean.DataBean mDataBean;

    @Override
    public int getLayoutId() {
        return R.layout.activity_charge_money;
    }

    @Override
    public void initView() {
        // 沉浸式状态栏
        QMUIStatusBarHelper.translucent(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            QMUIStatusBarHelper.setStatusBarLightMode(this);
        }
        ButterKnife.bind(this);
        initTopBar();
    }

    private void initTopBar() {
        mTopbar.setTitle(getResources().getString(R.string.str_charge_money));
        mTopbar.addLeftImageButton(R.drawable.ic_back, R.id.qmui_topbar_item_left_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void initData() {
        nodeid = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_NODE_ID, "");
        Intent intent = getIntent();
        mDataBean = (PurseListBean.DataBean) intent.getSerializableExtra("assetsDetailModel");
        pursetype = mDataBean.getPursetype();
        depositTip = intent.getStringExtra("depositTip");
        String config = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).getString(Constant.SP_CONFIG_INFO, "");
        LogUtils.dTag("config==", "config== " + config);
        if (!TextUtils.isEmpty(config)) {
            Gson gson = new Gson();
            ConfigBean.DataBean dataBean = gson.fromJson(config, ConfigBean.DataBean.class);
            if (dataBean != null) {
                eosdeposittip = dataBean.getEosdeposittip();
                if (!TextUtils.isEmpty(eosdeposittip)) {
                    eosdeposittip = new String(EncodeUtils.base64Decode(eosdeposittip));
                }
            }
        }
        purseId = mDataBean.getPurseid() + "";
//        balance = mDataBean.getBalance();
        balance = mDataBean.getBalanceformat();
        purseName = mDataBean.getPursename();
        purseunitname = mDataBean.getPurseunitname();
        if (ObjectUtils.isEmpty(depositTip)) {
            explainLayout.setVisibility(View.INVISIBLE);
        } else {
            explainLayout.setVisibility(View.VISIBLE);
        }
        getTransPurses();
    }

    @Override
    public void init() {

    }

    private void initPursesView() {
        int[] purseInfo = BlockchainUtils.getPurseIcon(purseName);
        int purseIcon = purseInfo[0];
        int newScale = purseInfo[1];
        GlideApp.with(this).load(ContextCompat.getDrawable(this, purseIcon)).into(childPurseIv);
        childPurseBalanceTv.setText(getResources().getString(R.string.str_balance_2) + " " + balance);
        childPurseNameTv.setText(purseName);
        if (pursetype == EOS_PURSE) {
            memoTv.setVisibility(View.VISIBLE);
            copyMemoBtn.setVisibility(View.VISIBLE);
            eosdeposittip = eosdeposittip.replace("\\n", "\n");
            explainTv.setText(eosdeposittip);
        } else {
            depositTip = depositTip.replace("\\n", "\n").replace("{{purse}}", purseName).replace("{{minamount}}", minnumber + purseunitname);
            memoTv.setVisibility(View.GONE);
            copyMemoBtn.setVisibility(View.GONE);
            explainTv.setText(depositTip);
        }

    }

    public void getCheckedPosition(String purseName) {
        for (int i = 0; i < pursesList.size(); i++) {
            BlockchainPursesBean.DataBean desktopBean = pursesList.get(i);
            String name = desktopBean.getPursename();
            if (ObjectUtils.equals(name, purseName)) {
                balance = desktopBean.getBalance() + "";
                purseconfigid = desktopBean.getPurseconfigid() + "";
                minnumber = desktopBean.getMindepositamount();
                purseunitname = desktopBean.getPurseunitname();
                pursetype = desktopBean.getPursetype();
                selPosition = i;
                return;
            }
        }
    }

    private void save2Album(Bitmap bitmap) {
        File appDir = new File(Environment.getExternalStorageDirectory(), "/uetoken/img");
        if (!appDir.exists()) appDir.mkdir();
        File file = new File(appDir, System.currentTimeMillis() + ".png");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            onSaveSuccess(file);
        } catch (IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.showShort(R.string.str_save_qrcode_fail);
                }
            });
            e.printStackTrace();
        }
    }

    private void onSaveSuccess(final File file) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
                ToastUtils.showShort(R.string.str_save_qrcode_succeed);
            }
        });
    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws
            IOException {
        dissmissDialog();
        LogUtils.dTag("onSuccessResponse==", "onSuccessResponse== response = " + response + " requestCode = " + requestCode);
        switch (requestCode) {
            case REQUEST_NETWORK_BLOCKCHAIN_PURSE_LIST:
                BlockchainPursesBean blockchainPursesListBean = new Gson().fromJson(response, BlockchainPursesBean.class);
                if (blockchainPursesListBean.getResult() > 0) {
                    pursesList = blockchainPursesListBean.getData();
                    getCheckedPosition(purseName);
                    initPursesView();
                    getPurseAddressByPurse();
                    if (mCurrencySelectPopWindow == null) {
                        mCurrencySelectPopWindow = new CurrencySelectPopWindow(ChargeMoneyActivity.this, pursesList, selPosition);
                        mCurrencySelectPopWindow.createPopup();
                        mCurrencySelectPopWindow.setAnimationStyle(R.style.dialogSlideAnim);
                        mCurrencySelectPopWindow.setOnPurseListener(this);
                    }
                } else {
                    ToastUtils.showShort(blockchainPursesListBean.getMessage());
                }
                break;
            case NETWORK_REQUEST_PURSE_ADDRESS:
                //{"data":{"purseaddress":"mvfHma1omgo29gWT1km7puCA4gcdMdfYvb"},"result":1,"message":"成功"}
                try {
                    JSONObject res = new JSONObject(response);
                    int result = res.getInt("result");
                    String message = res.getString("message");
                    if (result > 0) {
                        JSONObject data = new JSONObject(res.getString("data"));
                        purseaddress = data.getString("purseaddress");
                        addressMoneyTv.setText(purseaddress);
                        bitmap = ZXingUtils.createQRImage(purseaddress, SizeUtils.dp2px(150), SizeUtils.dp2px(150));
                        chargeMoneyQRIv.setImageBitmap(bitmap);

                        memoaddress = data.getString("memo");
                        memoTv.setText(memoaddress);
                    } else {
                        ToastUtils.showShort(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;

        }
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {

    }

    @Override
    public void onSelPurse(BlockchainPursesBean.DataBean pursesBean) {
        purseconfigid = pursesBean.getPurseconfigid() + "";
        purseName = pursesBean.getPursename();
        balance = pursesBean.getBalance() + "";
        minnumber = pursesBean.getMindepositamount();
        purseunitname = pursesBean.getPurseunitname();
        pursetype = pursesBean.getPursetype();
        getPurseAddressByPurse();
        initPursesView();
        mCurrencySelectPopWindow.dismiss();
    }

    @OnClick({R.id.purseLayout, R.id.saveQRBtn, R.id.copyAddressBtn, R.id.copyMemoBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.purseLayout:
                mCurrencySelectPopWindow.showAtLocation(goinLayout, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.saveQRBtn:
                save2Album(bitmap);
                break;
            case R.id.copyAddressBtn:
                ClipboardHelper.getInstance(this).copyText("address", purseaddress);
                ToastUtils.showShort(R.string.str_copy_succeed);
                break;
            case R.id.copyMemoBtn:
                ClipboardHelper.getInstance(this).copyText("memo", memoaddress);
                ToastUtils.showShort(R.string.str_copy_succeed);
                break;
        }
    }

    private void getTransPurses() {
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getTransPurses(), REQUEST_NETWORK_BLOCKCHAIN_PURSE_LIST, Params.getTransPursesParams(nodeid));
    }

    private void getPurseAddressByPurse() {
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getPurseAddressByPurse(), NETWORK_REQUEST_PURSE_ADDRESS, Params.getPurseAddressByPurseParams(nodeid, purseconfigid));
    }
}
